package com.webchat.pgc.service.sys;

import com.webchat.common.bean.APIPageResponseBean;
import com.webchat.common.service.RedisService;
import com.webchat.domain.vo.request.sys.SysDataDictionaryCategoryRequestVO;
import com.webchat.domain.vo.response.sys.SysDataDictionaryCategoryBaseVO;
import com.webchat.pgc.repository.dao.sys.ISysDataDictionaryCategoryDAO;
import com.webchat.pgc.repository.dao.sys.ISysDataDictionaryDAO;
import com.webchat.pgc.repository.entity.sys.SysDataDictionaryCategory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据字典分类服务
 *
 * @author SongRenShuo
 * @date 2025/06/25
 */
@Service
public class SysDataDictionaryCategoryService {

    @Autowired
    private ISysDataDictionaryCategoryDAO sysDataDictionaryCategoryDAO;
    @Autowired
    private ISysDataDictionaryDAO sysDataDictionaryDAO;
    @Autowired
    private RedisService redisService;

    /**
     * 创建或者更新数据字典分类
     *
     * @param requestVO 请求 VO
     * @return {@link Long }
     */
    public Long save(SysDataDictionaryCategoryRequestVO requestVO) {
        parameterValidation(requestVO);

        Long id = requestVO.getId();
        if (id == null) {
            // 新增数据
            long countDistinctByCode = sysDataDictionaryCategoryDAO.countDistinctByCode(requestVO.getCode());
            Assert.isTrue(countDistinctByCode == 0, "字典分类编码已存在");
            long countDistinctByName = sysDataDictionaryCategoryDAO.countDistinctByName(requestVO.getName());
            Assert.isTrue(countDistinctByName == 0, "字典分类名称已存在");
        } else {
            // 修改数据
            long countDistinctByCode = sysDataDictionaryCategoryDAO.countDistinctByCodeAndIdNot(requestVO.getCode(), id);
            Assert.isTrue(countDistinctByCode == 0, "字典分类编码已存在");
            long countDistinctByName = sysDataDictionaryCategoryDAO.countDistinctByNameAndIdNot(requestVO.getName(), id);
            Assert.isTrue(countDistinctByName == 0, "字典分类名称已存在");
        }

        return sysDataDictionaryCategoryDAO.save(convert(requestVO)).getId();
    }


    /**
     * 删除数据
     *
     * @param categoryId 主键
     * @param userId     用户ID
     * @return boolean
     */
    public boolean delete(Long categoryId, String userId) {
        Assert.notNull(categoryId, "字典分类ID不能为空");
        long countDistinctByCategoryId = sysDataDictionaryDAO.countDistinctByCategoryId(categoryId);
        Assert.isTrue(countDistinctByCategoryId == 0, "此分类下存在数据字典，无法删除！");
        sysDataDictionaryCategoryDAO.deleteById(categoryId);
        return true;
    }


    /**
     * 分页查询
     *
     * @param code     编号
     * @param name     名称
     * @param pageNo   页码
     * @param pageSize 每页条数
     * @return {@link APIPageResponseBean }<{@link SysDataDictionaryCategoryBaseVO }>
     */
    public APIPageResponseBean<SysDataDictionaryCategoryBaseVO> page(String code, String name, Integer pageNo, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, Sort.by(Sort.Direction.DESC, "id"));

        boolean notBlankCode = StringUtils.isNotBlank(code);
        boolean notBlankName = StringUtils.isNotBlank(name);

        Page<SysDataDictionaryCategory> dataDictionaryCategoryEntities = sysDataDictionaryCategoryDAO
                .findByCodeAndNameLike(notBlankCode ? code : null,
                        notBlankName ? name : null, pageable);

        List<SysDataDictionaryCategoryBaseVO> vos = new ArrayList<>();
        long totalElements = 0L;
        if (dataDictionaryCategoryEntities != null && CollectionUtils.isNotEmpty(dataDictionaryCategoryEntities.getContent())) {
            totalElements = dataDictionaryCategoryEntities.getTotalElements();
            vos = dataDictionaryCategoryEntities.getContent().stream().map(this::convert).collect(Collectors.toList());
        }
        return APIPageResponseBean.success(pageNo, pageSize, totalElements, vos);
    }

    /**
     * 列表查询 - 数据字典分类
     *
     * @return {@link List }<{@link SysDataDictionaryCategoryBaseVO }>
     */
    public List<SysDataDictionaryCategoryBaseVO> list() {

        List<SysDataDictionaryCategory> dataDictionaryCategoryEntities = sysDataDictionaryCategoryDAO.findAll();

        List<SysDataDictionaryCategoryBaseVO> vos = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dataDictionaryCategoryEntities)) {
            vos = dataDictionaryCategoryEntities.stream().map(this::convert).collect(Collectors.toList());
        }
        return vos;

    }

    /**
     * 参数验证
     *
     * @param requestVO 请求 VO
     */
    private static void parameterValidation(SysDataDictionaryCategoryRequestVO requestVO) {
        Assert.hasText(requestVO.getCode(), "字典分类编码不能为空");
        Assert.hasText(requestVO.getName(), "字典分类名称不能为空");
    }

    /**
     * 转换
     *
     * @param requestVO 请求 VO
     * @return {@link SysDataDictionaryCategory }
     */
    private SysDataDictionaryCategory convert(SysDataDictionaryCategoryRequestVO requestVO) {

        String operator = requestVO.getOperator();
        Long id = requestVO.getId();
        Date now = new Date();
        SysDataDictionaryCategory dataDictionaryCategory;
        if (id != null) {
            dataDictionaryCategory = sysDataDictionaryCategoryDAO.findById(id).orElse(null);
            Assert.notNull(dataDictionaryCategory, "数据字典分类不存在");
        } else {
            dataDictionaryCategory = new SysDataDictionaryCategory();
            dataDictionaryCategory.setCreateBy(operator);
            dataDictionaryCategory.setCreateDate(now);
        }
        dataDictionaryCategory.setCode(requestVO.getCode());
        dataDictionaryCategory.setName(requestVO.getName());
        dataDictionaryCategory.setUpdateBy(operator);
        dataDictionaryCategory.setUpdateDate(now);
        return dataDictionaryCategory;
    }

    /**
     * 转换
     *
     * @return {@link SysDataDictionaryCategoryBaseVO }
     */
    private SysDataDictionaryCategoryBaseVO convert(SysDataDictionaryCategory dataDictionaryCategory) {
        if (dataDictionaryCategory == null) {
            return null;
        }
        SysDataDictionaryCategoryBaseVO dataDictionaryCategoryBaseVo = new SysDataDictionaryCategoryBaseVO();
        BeanUtils.copyProperties(dataDictionaryCategory, dataDictionaryCategoryBaseVo);
        return dataDictionaryCategoryBaseVo;
    }


}
